package com.eightbears.beboy.ui.login;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.eightbears.beboy.MainActivity;
import com.eightbears.beboy.R;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.util.CommonAPI;
import com.eightbears.beboy.base.util.CommonUtils;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.InputMethodUtils;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.ShowToast;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.entity.UserEntity;
import com.eightbears.beboy.entity.WeiChatEntity;
import com.eightbears.beboy.entity.status.Status_Error;
import com.eightbears.beboy.ui.AgreementActivity;
import com.pnikosis.materialishprogress.ProgressWheel;
import com.socks.library.KLog;
import com.umeng.analytics.MobclickAgent;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jiguang.share.android.api.AuthListener;
import cn.jiguang.share.android.api.JShareInterface;
import cn.jiguang.share.android.api.Platform;
import cn.jiguang.share.android.model.AccessTokenInfo;
import cn.jiguang.share.android.model.BaseResponseInfo;
import cn.jiguang.share.wechat.Wechat;
import okhttp3.Call;

import static com.eightbears.beboy.base.util.CommonAPI.ERROR_CEDE_LOGIN_UNREGISTER_40104;

public class LoginActivity extends BaseActivity {

    public static final String PARAMS_REGISTER_PHONE = "registerPhone";
    public static final String PARAMS_REGISTER_CODE = "registercode";

    private int millisInFuture = 30000;
    private int countDownInterval = 1000;

    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.tv_login_tip)
    TextView tv_login_tip;
    @BindView(R.id.ll_back)
    LinearLayout ll_back;
    @BindView(R.id.et_phone_num)
    EditText et_phone_num;
    @BindView(R.id.btn_get_code)
    TextView btn_get_code;
    @BindView(R.id.et_code)
    EditText et_code;
    @BindView(R.id.btn_login)
    Button btn_login;
    @BindView(R.id.iv_weixin_login)
    ImageView iv_weixin_login;
    @BindView(R.id.progress_wheel)
    ProgressWheel progress_wheel;
    @BindView(R.id.cb_agree)
    CheckBox cb_agree;
    @BindView(R.id.view_loading)
    View view_loading;
    @BindView(R.id.tv_loading_text)
    TextView tv_loading_text;


    private String securityCode;
    private String phoneNum;
    private boolean isChecked;
    private String id, key, loginType;
    private TextWatcher watcher;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
        initData();
        initEvent();
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        ll_back.setVisibility(View.GONE);
        tv_title.setText(getText(R.string.text_login));
        tv_loading_text.setText(R.string.alert_for_wchat_login);
        tv_login_tip.setText(Html.fromHtml(getText(R.string.alert_login_tip).toString()));
    }

    @Override
    protected void initData() {
    }

    @Override
    protected void initEvent() {
        if(null == watcher) {
            watcher = new TextWatcher() {

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    KLog.e(count);

                }

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    if (s.length() == 11) {
                        replaceButtonClickable();
                    } else {
                        replaceButtonUnable();
                    }
                }
            };

        }
        et_phone_num.addTextChangedListener(watcher);
        cb_agree.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                LoginActivity.this.isChecked = isChecked;
            }
        });
    }


    @OnClick(R.id.btn_get_code)
    void getCode() {
        if (!validPhoneNum()) {
            return;
        }
        progress_wheel.setVisibility(View.VISIBLE);
        replaceButtonUnable();
        eventButtonUnable();
        timer.start();
        getNetCodeData();
    }

    @OnClick(R.id.btn_login)
    void sendLogin() {
        if (validPhoneNum() && validSecurityCode()) {
            if (!isChecked) {
                ShowToast.showShortToast(getString(R.string.alert_please_read));
                return;
            }
            progress_wheel.setVisibility(View.VISIBLE);
            replaceParams(phoneNum, securityCode, "sms");
            replaceLoginUnable();
            login();
        }

    }

    @OnClick(R.id.tv_pass_login)
    void passLogin() {
        startLocalActivity(this, PasswordLoginActivity.class);
    }

    @OnClick(R.id.tv_login_tip)
    void loginTip() {
        startLocalActivity(this, AgreementActivity.class);
    }

    @OnClick(R.id.iv_weixin_login)
    void wchatLogin() {
        view_loading.setVisibility(View.VISIBLE);
        if (!CommonUtils.isWeixinAvilible(mContext)) {
            view_loading.setVisibility(View.GONE);
            ShowToast.showLongToast(getString(R.string.text_install_wchat));
            return;
        }
        wxLogin();
    }

    // 微信登录
    public void wxLogin() {
        JShareInterface.authorize(Wechat.Name, mAuthListener);
    }

    /**
     * 获取网络信息请求验证码接口
     */
    private void getNetCodeData() {
        //请求网络
        OkHttpUtils.post().url(CommonAPI.URL_VERIFICATION_CODE)
                .addParams("mobile", phoneNum)//请求带上11位手机号码
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                progress_wheel.setVisibility(View.GONE);
                ShowToast.showShortToast(R.string.alert_code_send_success);
            }

            @Override
            public void onError(Call call, Exception e) {
                KLog.e(e.getMessage());
                progress_wheel.setVisibility(View.GONE);
                timer.cancel();
                replaceButtonClickable();
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(LoginActivity.this, status_error);
            }
        });
    }
        
    /**
     * 登录
     */
    private void login() {
        OkHttpUtils.post().url(CommonAPI.URL_LOGIN)
                .addParams("id", id)
                .addParams("key", key)
                .addParams("auth_type", loginType)
                .addParams("third_party", "weixin")
                .addParams("grant_type", "password")
                .addParams("refresh_token", "")
                .addParams("unique_id", CommonUtils.getAndroidId(getApplication()))
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                KLog.e(response);
                progress_wheel.setVisibility(View.GONE);
                UserEntity status_user = GsonUtil.fromJson(response, UserEntity.class);
                if (status_user.getStatus_code().equals(CommonAPI.CONNECTION_STATUS_SUCCESS)) {
                    SPUtil.saveUserInfo2Local(status_user);
                    MobclickAgent.onProfileSignIn(String.valueOf(status_user.getData().getUser_id()));  //友盟第三方账号登录统计
                    if (null != status_user.getData().getMobile() || !"".equals(status_user.getData().getMobile())
                            || null != status_user.getData().getNickname() || !"".equals(status_user.getData().getNickname())) {
                        startLocalActivity(LoginActivity.this, MainActivity.class);
                    }
                    view_loading.setVisibility(View.GONE);
                    InputMethodUtils.hindInputMethod(mContext);
                    finish();
                }
            }

            @Override
            public void onError(Call request, Exception e) {
                replaceLoginClickable();
                progress_wheel.setVisibility(View.GONE);
                view_loading.setVisibility(View.GONE);
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                if (status_error.getStatus_code() == ERROR_CEDE_LOGIN_UNREGISTER_40104) {
                    startLocalActivity(
                            LoginActivity.this, RegisterActivity.class,
                            new String[]{PARAMS_REGISTER_PHONE, PARAMS_REGISTER_CODE},
                            new String[]{phoneNum, securityCode});
                    return;
                }
                ErrorUtils.alertError(LoginActivity.this, status_error);
            }
        });
    }

    private boolean validSecurityCode() {
        securityCode = et_code.getText().toString().trim();
        if (securityCode.length() != 4) {
            ShowToast.showShortToast(R.string.error_security_code);
            return false;
        }
        return true;
    }

    private boolean validPhoneNum() {
        phoneNum = et_phone_num.getText().toString().trim();
        if (!CommonUtils.isPhoneNum(phoneNum)) {
            ShowToast.showShortToast(R.string.error_phone_num_input);
            return false;
        }
        return true;
    }

    private void replaceButtonClickable() {
        btn_get_code.setTextColor(getResources().getColor(R.color.text_color_fff));
        btn_get_code.setText(getText(R.string.text_get_security_code));
        btn_get_code.setBackgroundDrawable(getResources().getDrawable(R.drawable.background_circle_bead_blue_style));
        btn_get_code.setFocusable(true);
        btn_get_code.setClickable(true);
    }

    private void replaceButtonUnable() {
        btn_get_code.setTextColor(getResources().getColor(R.color.text_color_fff));
        btn_get_code.setBackgroundDrawable(getResources().getDrawable(R.drawable.background_gray_unable));
    }

    private void eventButtonUnable() {
        btn_get_code.setFocusable(false);
        btn_get_code.setClickable(false);
    }

    private void replaceLoginClickable() {
        btn_login.setTextColor(getResources().getColor(R.color.text_color_fff));
        btn_login.setText(getText(R.string.login));
        btn_login.setBackgroundDrawable(getResources().getDrawable(R.drawable.background_circle_bead_blue_style));
        btn_login.setFocusable(true);
        btn_login.setClickable(true);
    }

    private void replaceLoginUnable() {
        btn_login.setTextColor(getResources().getColor(R.color.text_other_info_color));
        btn_login.setText(R.string.alert_login);
        btn_login.setBackgroundDrawable(getResources().getDrawable(R.drawable.background_gray_unable));
        btn_login.setFocusable(false);
        btn_login.setClickable(false);
    }

    private void replaceParams(String id, String key, String logintype) {
        this.id = id;
        this.key = key;
        this.loginType = logintype;
    }




    CountDownTimer timer = new CountDownTimer(millisInFuture, countDownInterval) {
        @SuppressLint("SetTextI18n")
        @Override
        public void onTick(long millisUntilFinished) {

            btn_get_code.setText(millisUntilFinished / countDownInterval + getString(R.string.alert_code_count_down));
        }

        @Override
        public void onFinish() {
            replaceButtonClickable();
        }
    };


    AuthListener mAuthListener = new AuthListener() {
        @Override
        public void onComplete(Platform platform, int action, BaseResponseInfo data) {
            WeiChatEntity weiChatEntity = new WeiChatEntity();
            weiChatEntity.setAccess_token(((AccessTokenInfo) data).getToken());
            weiChatEntity.setRefresh_token(((AccessTokenInfo) data).getRefeshToken());
            weiChatEntity.setOpenid(((AccessTokenInfo) data).getOpenid());
            //友盟第三方账号登录统计
            MobclickAgent.onProfileSignIn("WX", ((AccessTokenInfo) data).getOpenid());
            SPUtil.putWChat(weiChatEntity);
            replaceParams(SPUtil.getWChat().getOpenid(), SPUtil.getWChat().getAccess_token(), "third_party");
            login();
        }

        @Override
        public void onError(Platform platform, int action, int errorCode, Throwable error) {
            view_loading.setVisibility(View.GONE);
        }

        @Override
        public void onCancel(Platform platform, int action) {
            ShowToast.showShortToast(getString(R.string.alert_cancel_wchat_login));
            view_loading.setVisibility(View.GONE);
        }
    };
}
